var app = getApp();
var wxCharts = require('../../../utils/wxcharts.js');
var common = require('../../common/common.js')
var bmap = require('../../common/bmap-wx.js');
var url = app.globalData.url;
var error = common.error;
var lineChart01 = null;
/* var touchDot = 0; //触摸时的原点
var time = 0; // 时间记录，用于滑动时且时间小于1s则执行左右滑动
var interval = ""; // 记录/清理时间记录 */
var user = wx.getStorageSync('account');
var pwd = wx.getStorageSync('password');
var Token = wx.getStorageSync('Token');

Page({
  data: {
    navbar: ['今日', '本周', '本月', '本年'],
    currentTab: 0,
    isMainChartDisplay: true,
  },  
  navbarTap: function(e) {
    var that = this
    that.setData({
      currentTab: e.currentTarget.dataset.idx
    })
    var locIDs = that.data.locIDs
    that.chartData(locIDs)    
  },
  touchHandler01: function (e) {
    console.log('今日触屏')
    console.log(lineChart01.getCurrentDataIndex(e));
    console.log(e)
    lineChart01.showToolTip(e, {
      // background: '#7cb5ec',
      format: function (item, category) {
        return category + ':00' + ' ' + item.name + ':' + item.data
      }
    });
  },
  // 今日
  createSimulationData: function() {
    var categories = [];
    var data = [];
    for (var i = 8; i < 24; i++) {
      //categories.push('2016-' + (i + 1));
      categories.push(i + 1);
      data.push(Math.random() * (20 - 10) + 10);
    }
    return {
      categories: categories,
      data: data
    }
  },
  //本周
  createSimulationDataWeek: function() {
    var categories = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    var data = [];
    return {
      categories: categories,
      data: data
    }
  },
  //本月
  createSimulationDataMonth: function() {
    var categories = [];
    var data = [];
    for (var i = 0; i < 5; i++) {
      categories.push('第' + (i + 1) + '周');
      //categories.push(i + 1);
      data.push(Math.random() * (20 - 10) + 10);
    }
    data[4] = null;
    return {
      categories: categories,
      data: data
    }
  },
  //本年
  createSimulationDataYear: function() {
    var categories = [];
    var data = [];
    for (var i = 0; i < 4; i++) {
      categories.push('第' + (i + 1) + '季');
      //categories.push(i + 1);
      data.push(Math.random() * (20 - 10) + 10);
    }
    // data[4] = null;
    return {
      categories: categories,
      data: data
    }
  },
  onLoad: function(options) {
    console.log(options)
    var that = this;
    var locIDs = that.options.locIDs
    that.setData({
      locIDs: locIDs
    })
    wx.setNavigationBarTitle({
      title: options.shop,
    })
    that.chartData(locIDs)
    /** 
     * 获取系统信息 
     */
    wx.getSystemInfo
    ({
      success: function(res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
  },
  /**
   * 请求函数
  */
  chartData: function (locIDs){
    var that = this;
    var currentTab = that.data.currentTab;
    var Token = wx.getStorageSync('Token');
    that.setData({
      Token: Token,
      currentTab: currentTab
    });
    console.log(locIDs)
    //请求摘要数据
    var params = {
      Token: Token,
      Type: currentTab,
      WithSalesData: true,
      WithComparedData: true,
      LocationIDs: locIDs
    }
    common.requestLoading(url + '/data', params, '正在加载数据', function (res) {
      console.log(res)
      var Arr = ['09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'];
      var weekArr = ['1', '2', '3', '4', '5']; //本周核对
      var dateArr = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']; //本周
      var yearArr = ['1', '2', '3', '4']
      var basic = res.BasicData
      var comBasic = res.ComparedData
      var counts = basic.CustTrafficData //客流量
      var comCounts = comBasic.CustTrafficData //比较客流量
      var sales = basic.SalesData // 下单数
      var comSales = comBasic.SalesData // 比较下单数
      var WCustTrafficArr = []
      var WcountsArr = []
      var comWCustTrafficArr = []
      var comWcountsArr = []
      function timesDataKey(times, counts, WCustTrafficArr, sales) {
        for (var i = 0; i < counts.length; i++) {
          var lab = counts[i].LABEL;
          var n = times.indexOf(lab);
          WCustTrafficArr[n] = counts[i].IN; //客流量
          
        }
        for (var j = 0; j < sales.length; j++) {
          //var sales = res.BasicData.SalesData
          var saleTime = sales[j].LABEL;
          var time = times.indexOf(saleTime);
          WcountsArr[time] = sales[j].Counts; //下单数      
        }
      }
      function timesDataCompare(times) {
        for (var i = 0; i < comCounts.length; i++) {
          var lab = comCounts[i].LABEL;
          var n = times.indexOf(lab);
          comWCustTrafficArr[n] = comCounts[i].IN; //比较Footfall
        
        }
        for (var j = 0; j < comSales.length; j++) {
          var saleTime = comSales[j].LABEL;
          var Countstime = times.indexOf(saleTime);
          comWcountsArr[Countstime] = comSales[j].Counts; //比较下单数
        }
      }
      timesDataCompare(Arr)
      timesDataCompare(weekArr)
      timesDataCompare(dateArr)
      timesDataCompare(yearArr)
      timesDataKey(Arr, counts, WCustTrafficArr, sales)
      timesDataKey(weekArr, counts, WCustTrafficArr, sales)
      timesDataKey(dateArr, counts, WCustTrafficArr, sales)
      timesDataKey(yearArr, counts, WCustTrafficArr, sales)
      //成交率
      var rate = common.cal(WcountsArr, WCustTrafficArr)
      //timesDataKey(weekArr, sales, WCustTrafficArr)

      common.calUndefined(WcountsArr)
      common.calUndefined(comWcountsArr)
      common.calUndefined(WCustTrafficArr)   //客流量
      common.calUndefined(comWCustTrafficArr) //比较客流量
      var simulationData = that.createSimulationData().categories;
      var simulationDataMonth = that.createSimulationDataMonth().categories;
      var simulationDataYear = that.createSimulationDataYear().categories;
      var simulationDataWeek = that.createSimulationDataWeek().categories;
      var lineCanvas01 = lineCanvas01
      var contrast = '昨日(同期客流量对比)'
      var windowWidth = 320;
      try {
        var res = wx.getSystemInfoSync();
        windowWidth = res.windowWidth;
      } catch (e) {
        console.error('getSystemInfoSync failed!');
      }
      switch (currentTab) {
        case 0:
          lineChart01 = Chart('lineCanvas01', simulationData);
          console.log(lineChart01)
          var lineChart02 = ChartCount('lineCanvas02', simulationData);
          break;
        case 1:
          var lineChart2 = Chart('lineCanvas2', simulationDataWeek);
          var lineChart21 = ChartCount('lineCanvas21', simulationDataWeek);
          break;
        case 2:
          var lineChart3 = Chart('lineCanvas3', simulationDataMonth);
          var lineChart31 = ChartCount('lineCanvas31', simulationDataMonth);
          break;
        case 3:
          var lineChart4 = Chart('lineCanvas4', simulationDataYear);
          var lineChart41 = ChartCount('lineCanvas41', simulationDataYear);
          break;
      }
      
      /* if (WCustTrafficArr.length == 0 || WcountsArr.length == 0){
        wx.showModal({
          title: '提示',
          content: '当前时间暂无数据信息，请稍后重试！',
          showCancel: false,
          success: function (res) {
            if (res.confirm) 
            {
              switch (currentTab) {
                case 0:
                 lineChart01 = Chart('lineCanvas01', simulationData);
                  break;
                case 1:
                  var lineChart2 = Chart('lineCanvas2', simulationDataWeek);
                  break;
                case 2:
                  var lineChart3 = Chart('lineCanvas3', simulationDataMonth);
                  break;
                case 3:
                  var lineChart4 = Chart('lineCanvas4', simulationDataYear);
                  break;
              }
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })

      }else{
        switch (currentTab) {
          case 0:
            lineChart01 = Chart('lineCanvas01', simulationData);
            console.log(lineChart01)
            var lineChart02 = ChartCount('lineCanvas02', simulationData);
            break;
          case 1:
            var lineChart2 = Chart('lineCanvas2', simulationDataWeek);
            var lineChart21 = ChartCount('lineCanvas21', simulationDataWeek);
            break;
          case 2:
            var lineChart3 = Chart('lineCanvas3', simulationDataMonth);
            var lineChart31 = ChartCount('lineCanvas31', simulationDataMonth);
            break;
          case 3:
            var lineChart4 = Chart('lineCanvas4', simulationDataYear);
            var lineChart41 = ChartCount('lineCanvas41', simulationDataYear);
            break;
        }
        
      } */
      
      function Chart(canvasId, categories) {
        return new wxCharts({
          canvasId: canvasId,
          type: 'column',
          categories: categories,
          animation: true,
          dataLabel: true,
          // background: '#f5f5f5',
          series: [
            {
              name: '今日',
              //data: simulationData.data,
              data: !WCustTrafficArr.length ? new Array(categories.length).fill(0) : WCustTrafficArr,
              dataLabel: true,
              format: function (val, name) {
                return val;
              }
            },
            {
              name: '昨日(同期客流量对比)',
              data: !comWCustTrafficArr.length ? new Array(categories.length).fill(0) : comWCustTrafficArr,
              format: function (val, name) {
                return val;
              }
            },
            // {
            //   name: '成交率(%)',
            //   data: [2, 0, 0, 3, 6, 7, 9],
            //   format: function (val, name) {
            //     return val;
            //   }
            // }
          ],
          xAxis: {
            disableGrid: true
          },
          yAxis: {
            // title: '成交金额 (万元)',
            format: function (val) {
              return val.toFixed(2);
            },
            min: 0,
            disabled: true
          },
          width: windowWidth,
          height: 260,

          dataPointShape: true,
          extra: {
            lineStyle: 'curve'
          }
        });
      }
      function ChartCount(canvasId, categories) {
       return new wxCharts({
          canvasId: canvasId,
          type: 'column',
          categories: categories,
          animation: true,
          dataLabel: true,
          series: [
            {
              name: '今日',
              //data: simulationData.data,
              data: !WcountsArr.length ? new Array(WCustTrafficArr.length).fill(0) : WcountsArr,
              dataLabel: true,
              format: function (val, name) {
                return val;
              }
            },
            {
              name: '昨日(同期开单数)',
              data: comWcountsArr.length ? comWcountsArr : new Array(categories.length).fill(0) ,
              format: function (val, name) {
                return val;
              }
            },
            // {
            //   name: '成交率(%)',
            //   data: [2, 0, 0, 3, 6, 7, 9],
            //   format: function (val, name) {
            //     return val;
            //   }
            // }
          ],
          xAxis: {
            disableGrid: true
          },
          yAxis: {
            // title: '成交金额 (万元)',
            format: function (val) {
              return val.toFixed(2);
            },
            min: 0,
            disabled: true
          },
          width: windowWidth,
          height: 260,
          dataPointShape: true,
          extra: {
            lineStyle: 'curve'
          }
        });
      }
    },error)
  } 
});